<template>
  <div>
    <div v-if="succVisible == 0">
      <a-button type="primary" :loading="msgLoading" class="d-a-center" style="margin-bottom: 20px" @click="sendEmail">发送</a-button>
      <!-- 头部 -->
      <a-form ref="searchRef" :model="emailForm" :hideRequiredMark="true">
        <a-row>
          <a-col :span="14" :offset="0">
            <a-form-item name="emailForm.recipientPhone" label="收件人">
              <!-- <a-input placeholder="请输入收件人邮箱账号" v-model:value="emailForm.recipientPhone"></a-input> -->
              <a-cascader
                v-model:value="value"
                :options="options"
                @change="reChange"
                :show-search="{ filter }"
                placeholder="请选择收件人"
              />
            </a-form-item>
          </a-col>
          <div class="" style="margin-left: 10px; font-size: 18px">@loto.com</div>
          <a-col :span="14" :offset="0">
            <a-form-item name="emailForm.subject" label="主&nbsp;&nbsp;&nbsp;&nbsp;题">
              <a-input placeholder="请输入邮件主题" v-model:value="emailForm.subject"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="14" :offset="0">
            <a-form-item name="emailForm.person" label="抄&nbsp;&nbsp;&nbsp;&nbsp;送">
              <a-input placeholder="请添加抄送人" v-model:value="emailForm.person" @click="openSelect">
                <template #prefix>
                  <plus-circle-outlined />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- list-type="picture" -->
      <div style="width: 100%">
        <a-upload
          v-model:file-list="fileList"
          :custom-request="uploadFile"
          :before-upload="beforeUpload"
          @change="handleChange"
          @remove="remove"
          class=""
          accept=".rar,.zip,.pdf,.jpg,.png,.webp,.docx,.ppt,.pptx,.jpeg,.xls,.doc,.xlsx"
          :max-count="9"
        >
          <div class="df">
            <div style="margin-left: 2%; width: 70px; font-size: 16px">添加附件</div>
            <paper-clip-outlined style="font-size: 15px" class="d-a-center" />
            <div style="color: #81b603; font-size: 15px" class="d-a-center">（50M）</div>
          </div>
        </a-upload>
      </div>
      <a-modal v-model:visible="visible" title="选择抄送人" :maskClosable="false" centered width="900px" @ok="confirm">
        <!-- <a-input-search v-model:value="searchValue" style="margin-bottom: 8px" placeholder="请输入关键字进行搜索" /> -->
        <a-tree
          :tree-data="list"
          checkable
          :expanded-keys="expandedKeys"
          :auto-expand-parent="autoExpandParent"
          @expand="onExpand"
          @check="checkSelect"
          style="width: 50%"
        >
          <template #title="{ title }">
            <span v-if="title.indexOf(searchValue) > -1">
              {{ title.substr(0, title.indexOf(searchValue)) }}
              <span style="color: #f50">{{ searchValue }}</span>
              {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
            </span>
            <span v-else>{{ title }}</span>
          </template>
        </a-tree>
      </a-modal>
      <tinymce ref="editor" :value="emailForm.content" @input="tinymceInput" style="margin-top: 15px"></tinymce>
    </div>
    <block v-if="succVisible == 1" class="d-c-center">
      <div class="" style="width: 100px">
        <img class="succ-fail" src="@/assets/img/email/email-succ.png" alt="email-succ" />
        <div class="d-j-center" style="margin-top: 10px; font-size: 20px; font-weight: 500; color: #74c041">发送成功</div>
      </div>
    </block>
    <block v-if="succVisible == 2" class="d-c-center">
      <div class="" style="width: 100px">
        <img class="succ-fail" src="@/assets/img/email/email-fail.png" alt="email-fail" />
        <div class="d-j-center" style="margin-top: 10px; font-size: 20px; font-weight: 500; color: #ff1a2e">发送失败</div>
      </div>
    </block>
  </div>
</template>
<script>
import * as apil from '@/api/setting/index'
import { useRoute, useRouter } from 'vue-router'
import router from '@/router/index.js'
import tinymce from '@/components/common/tinymce/tinymce'
import { writeAnEmail, uploadPicture } from '@/api/email/index.js'
import UploadFile from '@/components/common/UploadFile.vue'
import { reactive, ref, toRefs, watch, computed, defineComponent, createVNode } from 'vue'
import {
  CloseOutlined,
  PlusCircleOutlined,
  ApartmentOutlined,
  // 附件
  PaperClipOutlined
} from '@ant-design/icons-vue'
import { Modal, message, Empty, Upload } from 'ant-design-vue'
import { number } from 'echarts'
export default {
  components: {
    tinymce,
    CloseOutlined,
    PlusCircleOutlined,
    ApartmentOutlined,
    // 附件
    PaperClipOutlined
  },
  setup() {
    const router = useRouter()
    const searchRef = ref('')
    const data = reactive({
      emailForm: {
        person: ''
      },
      visible: false,
      recipientList: [],
      succVisible: 0,
      fileList: [],
      // endFileLength: [],
      handleList: []
    })
    const options = ref([])
    const filter = (inputValue, path) => {
      return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
    }
    const reChange = e => {
      console.log('reeeeeeeeee', e)
      data.emailForm.recipientPhone = e[1]
      console.log('data.emailForm.recipientPhone', data.emailForm.recipientPhone)
    }
    const list = ref([])
    //展开的key
    const expandedKeys = ref([])
    //搜索关键字
    const searchValue = ref('')
    //是否展开树
    const autoExpandParent = ref(true)
    // 展开收起触发
    const onExpand = keys => {
      expandedKeys.value = keys
      autoExpandParent.value = false
    }
    const beforeUpload = file => {
      console.log(file, 888888888888)
      if (file.size > 10485760) {
        message.error('上传失败，单个附件大小限制为10M，请重新上传！')
        return Upload.LIST_IGNORE
      }
      console.log('99999999999999999', data.handleList.length)
      if (data.handleList.length == 9) {
        message.error('上传失败，附件个数限制为9个！')
        return Upload.LIST_IGNORE
      }
      const isRar = file.name.split('').slice(-4, file.name.length).join('') === '.rar'
      const isType =
        file.type === 'image/psd' ||
        file.type === 'image/bmp' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png' ||
        file.type === 'image/webp' ||
        file.type === 'image/gif' ||
        file.type === 'image/jpeg' ||
        file.type === 'application/pdf' ||
        file.type === 'application/msword' ||
        file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
        file.type === 'application/x-zip-compressed' ||
        file.type === 'application/vnd.openxmlformats-officedocument.presentationml.presentation' ||
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-powerpoint' ||
        file.type === 'application/vnd.ms-excel' ||
        isRar
      if (!isType) {
        message.error('文件格式错误，仅允许.zip,.rar,.pdf,.jpg,,jpeg,.png,.doc,.docx,.ppt,.pptx,xls,.xlsx格式文件!')
      }
      return isType || Upload.LIST_IGNORE
    }
    const handleChange = file => {
      console.log('fileList', file.fileList)
      file.fileList.forEach(f => {
        f.status = 'done'
      })
    }
    const uploadFile = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      // console.log(formData.get("file"), "上传图片传参");
      // console.log('文件大小', formData.get("file").size);
      let res = await uploadPicture(formData, 'email')
      if (res.success) {
        data.handleList.push({
          uid: file.file.uid,
          url: res.object,
          status: 'done',
          name: file.file.name,
          size: file.file.size
        })

        if (data.fileList.length <= 8) {
          data.fileList.push({
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name,
            size: file.file.size
          })
        }
      }
    }
    const remove = e => {
      console.log('remmove', e.uid)
      console.log('handleList', data.handleList)
      data.fileList = data.fileList.filter(i => {
        return i.uid != e.uid
      })
      data.handleList = data.handleList.filter(i => {
        return i.uid != e.uid
      })
      console.log('.handleList过滤后', data.handleList)
      // console.log('过滤后', data.fileList);
    }
    init()
    async function init() {
      data.loading = false
      console.log('初始化数据')
      // 部门列表
      apil.deparmentList().then(r => {
        r.object.forEach(async i => {
          // 人员列表
          let res = await apil.adminList({
            pageSize: 100,
            pageNum: 1,
            departmentId: i.id
          })
          if (res.success) {
            let childrenList = []
            let reChildrenList = []
            res.object.list.forEach(res1 => {
              childrenList.push({
                account: res1.id,
                title: res1.realName,
                key: res1.account
              })
              reChildrenList.push({
                account: res1.id,
                label: res1.realName,
                value: res1.account
              })
            })
            list.value.push({
              key: i.id,
              title: i.departmentName,
              children: childrenList
            })
            options.value.push({
              value: i.id,
              label: i.departmentName,
              children: reChildrenList
            })
          }
        })
      })
      console.log('list.value', list.value)
      console.log('options.value', options.value)
    }
    const sendEmail = async () => {
      let sumSize = 0
      data.emailForm.attachments = []
      data.fileList.forEach(i => {
        sumSize += i.size
        data.emailForm.attachments.push({
          fileName: i.name,
          filePath: i.url
        })
      })
      console.log(sumSize)
      if (data.emailForm.recipientPhone == '' || data.emailForm.recipientPhone == undefined) {
        message.error('请填写收件人信息！')
      } else if (!/^(?:(?:\+|00)86)?1\d{10}$/.test(data.emailForm.recipientPhone)) {
        message.error('请正确填写收件人信息！')
      } else if (data.emailForm.subject == '' || data.emailForm.subject == undefined) {
        message.error('请填写邮件主题！')
      } else if (data.emailForm.content == '' || data.emailForm.content == undefined) {
        message.error('请填写邮件内容！')
      } else {
        if (sumSize > 52428800) {
          message.error('上传失败，附件大小限制为50M，请重新上传！')
        } else {
          let copies = []
          data.recipientList.forEach(i => {
            copies.push({
              recipientId: i.account,
              recipientPhone: i.key
            })
          })
          data.emailForm.copies = copies
          console.log('最后的参数：', data.emailForm, data.emailForm.recipientPhone)
          let res = await writeAnEmail(data.emailForm)
          if (res.success) {
            console.log('接口调用', res)
            data.succVisible = 1
          } else {
            data.succVisible = 2
          }
        }
      }
    }
    //andt 组件方法 获取父级节点key
    const getParentKey = (key, tree) => {
      let parentKey
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some(item => item.key === key)) {
            parentKey = node.key
          } else if (getParentKey(key, node.children)) {
            parentKey = getParentKey(key, node.children)
          }
        }
      }
      return parentKey
    }
    const checkSelect = (e, v, ll) => {
      console.log(v.checkedNodes)
      data.recipientList = v.checkedNodes.filter(i => {
        return typeof i.key != 'number'
      })
      console.log(44555, data.recipientList)
    }
    watch(searchValue, value => {
      const expanded = list.value
        .map(item => {
          if (item.title.indexOf(value) > -1) {
            return getParentKey(item.key, list.value)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
      expandedKeys.value = expanded
      searchValue.value = value
      autoExpandParent.value = true
      console.log('autoExpandParent.value', autoExpandParent.value)
    })
    const fileList = ref([])
    const tinymceInput = e => {
      data.emailForm.content = e
    }
    const confirm = () => {
      data.emailForm.person = ''
      data.visible = false
      data.recipientList.forEach(i => {
        data.emailForm.person = i.title + ',' + data.emailForm.person
      })
      console.log(data.emailForm.person)
    }
    const methods = {
      reset() {
        console.log('重置111111')
        data.searchForm = {}
        // page.page = 1;
        init()
      },
      openSelect() {
        data.visible = true
        searchValue.value = ''
      }
    }
    return {
      ...toRefs(data),
      ...methods,
      value: ref([]),
      options,
      reChange,
      filter,
      fileList,
      remove,
      checkSelect,
      searchRef,
      confirm,
      tinymceInput,
      list,
      expandedKeys,
      searchValue,
      autoExpandParent,
      getParentKey,
      onExpand,
      sendEmail,
      uploadFile,
      beforeUpload,
      handleChange
    }
  }
}
</script>
<style scoped lang="less">
:deep(.ant-upload-list) {
  display: flex;
  flex-wrap: wrap;
}

/* tile uploaded pictures */
.upload-list-inline :deep(.ant-upload-list-item) {
  float: left;
  width: 200px;
  margin-right: 20px;
}

.upload-list-inline [class*='-upload-list-rtl'] :deep(.ant-upload-list-item) {
  float: right;
}

.succ-fail {
  width: 100px;
  height: 100px;
}
</style>
